package service

import (
	"SERVER/basic/config"
	__ "SERVER/basic/proto"
	"SERVER/handler/model"
	"context"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedUserServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	user := model.User{
		Username: in.Username,
		Password: in.Password,
	}
	if user.Id == 0 {
		return &__.LoginResp{
			Code: 500,
			Msg:  "该用户不存在",
		}, nil
	}

	if err := config.DB.Where("username = ? AND password = ?", in.Username, in.Password).Find(&user).Error; err != nil {
		return &__.LoginResp{
			Code: 500,
			Msg:  "用户名或密码错误",
		}, nil
	}
	return &__.LoginResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}

func (s *Server) ListPage(_ context.Context, in *__.ListPageReq) (*__.ListPageResp, error) {
	var goods []model.Goods
	if err := config.DB.Limit(int(in.PageSize)).Offset(int(in.Page)).Find(&goods).Error; err != nil {
		return &__.ListPageResp{
			Code: 500,
			Msg:  "查询失败",
		}, nil
	}
	return &__.ListPageResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}

func (s *Server) ListActivity(_ context.Context, in *__.ListActivityReq) (*__.ListActivityResp, error) {
	var activity []model.Activity
	if err := config.DB.Find(&activity).Error; err != nil {
		return &__.ListActivityResp{
			Code: 500,
			Msg:  "查询失败",
		}, err
	}
	return &__.ListActivityResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}

func (s *Server) DetailGoods(_ context.Context, in *__.DetailGoodsReq) (*__.DetailGoodsResp, error) {
	var goods model.Goods
	if err := config.DB.Where("id =?", in.Id).Find(&goods).Error; err != nil {
		return &__.DetailGoodsResp{
			Code: 500,
			Msg:  "查询失败",
		}, err
	}
	//redis
	config.RDB.Set(context.Background(), "goods", goods, 0).Val()

	return &__.DetailGoodsResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}

func (s *Server) ShowGoods(_ context.Context, in *__.ShowGoodsReq) (*__.ShowGoodsResp, error) {
	var goods model.Goods
	if err := config.DB.Where("id =?", in.Id).Find(&goods).Error; err != nil {
		return &__.ShowGoodsResp{
			Code: 500,
			Msg:  "查询失败",
		}, err
	}
	return &__.ShowGoodsResp{
		Code: 200,
		Msg:  "OK",
	}, nil
}
